package com.starsoft.frame.config;

import javax.annotation.PostConstruct;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.store.MemoryStoreEvictionPolicy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Component;

@Component
public class CacheConfig {

	@Autowired
	EhCacheCacheManager cacheManager;

	@PostConstruct
	public void setCache() {
		CacheManager cacheManagerEH = cacheManager.getCacheManager();
		
		setOrmCache(cacheManagerEH);
		
		String cacheName = "frameCache";
		cacheManagerEH.removeCache(cacheName);
		CacheConfiguration config = new CacheConfiguration(cacheName, 100000)
				.eternal(false)
				.timeToIdleSeconds(0)
				.timeToLiveSeconds(36000)
				.overflowToDisk(false)
				.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU);
		cacheManagerEH.addCache(new Cache(config));
		
		cacheName = "serviceCache";
		cacheManagerEH.removeCache(cacheName);
		config = new CacheConfiguration(cacheName, 100000)
				.eternal(false)
				.timeToIdleSeconds(0)
				.timeToLiveSeconds(600)
				.overflowToDisk(false)
				.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU);
		cacheManagerEH.addCache(new Cache(config));
	}

	private void setOrmCache(CacheManager cacheManagerEH){
		String cacheName = "ormCache";
		Cache cache = cacheManagerEH.getCache(cacheName);
		CacheConfiguration config = null;
		if(cache != null){
			config = cacheManagerEH.getCache(cacheName).getCacheConfiguration();
		} else {
			config = new CacheConfiguration(cacheName, 100000);
		}
		config.maxElementsInMemory(100000)
			.eternal(false)
			.timeToIdleSeconds(0)
			.timeToLiveSeconds(36000)
			.overflowToDisk(false)
			.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU);
		if(cache ==null){
			cacheManagerEH.addCache(new Cache(config));
		}
		
	}
	
}
